<script setup lang="ts">
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import { getPurchaseList, delPurchaseInfo } from '@/api/purchase/purchase-list.ts'
import type { PurchaseDetailModel } from '@/api/purchase/purchase-list.ts'
import PurchaseAdd from './purchase-add.vue'
import PurchaseDetail from './purchase-detail.vue'

import dayjs, { Dayjs } from 'dayjs'
import {ref} from "vue";


const value1 = ref<Dayjs>()


// 日期格式化
function onChange(value, dateString) {
  if (dateString !=''){
    console.log(value,'   ',dateString)
    formModel.purchaseDeparture = dayjs(dateString).format('YYYY-MM-DD')
  }else {
    formModel.purchaseDeparture = ""
  }
}

const purchaseStatusMap = {
  1: '暂存',
  2: '已保存',
  3: '作废',
}
const purchasePaymentStatusMap = {
  1: '未付款',
  2: '部分付款',
  3: '全部付款',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '采购单号',
    dataIndex: 'purchaseId',
  },
  {
    title: '本单日期',
    dataIndex: 'purchaseDeparture',
  },
  {
    title: '采购车辆',
    dataIndex: 'purchaseVehicle',
  },
  {
    title: '采购自动总价',
    dataIndex: 'purchaseTotalPrice',
  },
  {
    title: '实际采购总金额',
    dataIndex: 'purchaseActualAmount',
  },
  {
    title: '运费',
    dataIndex: 'purchaseFreight',
  },
  {
    title: '成本单价',
    dataIndex: 'purchaseUnitCost',
  },
  {
    title: '总斤数',
    dataIndex: 'purchaseTotal',
  },
  {
    title: '剩余结算总金额',
    dataIndex: 'remainSettlementAmount',
  },
  {
    title: '采购描述',
    dataIndex: 'purchaseDescribe',
  },
  {
    title: '采购人',
    dataIndex: 'purchaseUser',
  },
  {
    title: '采购状态',
    dataIndex: 'purchaseStatus',
  },
  {
    title: '采购单付款状态',
    dataIndex: 'purchasePaymentStatus',
  },

  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])
const loading = shallowRef(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 100,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总订单数：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
// 订单数据集
const dataSource = shallowRef<PurchaseDetailModel[]>([])
// 搜索条件
const formModel = reactive<PurchaseDetailModel>({
  purchaseId: undefined,
})

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getPurchaseList({
      ...formModel,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    })
    console.log('加载采购订单数据完成')
    console.log(data)
    dataSource.value = data?.list ?? []
    pagination.total = data?.count
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.purchaseId = undefined
  formModel.purchaseStatus = undefined
  formModel.purchasePaymentStatus = undefined
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: PurchaseDetailModel) {
  const close = message.loading('删除中......')
  try {
    const reqForm = ref<PurchaseDetailModel>({
      purchaseId: record.purchaseId,
    })
    const res = await delPurchaseInfo(reqForm.value)
    if (res.code === 200){
      await init()
      message.success('删除成功')
    }else {
      message.error(res.msg)
    }
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

function handleCheckAllChange(e: any) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

const purchaseAdd = ref<InstanceType<typeof PurchaseAdd>>()

// 进入添加采购单页面
async function handleAdd() {
  console.log('进入添加采购单页面')
  purchaseAdd.value?.open()
}

// 进入采购单编辑页面
async function handleEdit(record: PurchaseDetailModel) {
  // TODO 待补充仓库类型编号
  purchaseAdd.value?.open(record)
}

// 声明一个详情组件
const purchaseDetail = ref<InstanceType<typeof PurchaseDetail>>()
// 打开详情组件
async function handleDetail(record: PurchaseDetailModel) {
  purchaseDetail.value?.open(record)
}

/**
 * checkbox点击事件
 *
 */
function handleCheckChange(value: any) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="4">
            <a-form-item name="value1" label="采购单日期">
              <a-date-picker v-model:value="value1" @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="purchaseId" label="采购单号">
              <a-input v-model:value="formModel.purchaseId" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="purchaseStatus" label="采购状态">
              <a-select
                v-model:value="formModel.purchaseStatus"
              >
                <a-select-option value="1">
                  暂存
                </a-select-option>
                <a-select-option value="2">
                  已保存
                </a-select-option>
                <a-select-option value="3">
                  已作废
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item name="purchasePaymentStatus" label="采购单付款状态">
              <a-select
                v-model:value="formModel.purchasePaymentStatus"
              >
                <a-select-option value="1">
                  未付款
                </a-select-option>
                <a-select-option value="2">
                  部分付款
                </a-select-option>
                <a-select-option value="3">
                  全部付款
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="采购记录">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加采购记录
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="handleDelete(scope?.record as PurchaseDetailModel)">
                作废
              </a>
              <a @click="handleDetail(scope?.record as PurchaseDetailModel)">
                查看详情
              </a>
              <a @click="handleEdit(scope?.record as PurchaseDetailModel)">
                编辑
              </a>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'purchaseStatus'">
            <div gap-2>
              {{ purchaseStatusMap[scope?.record?.purchaseStatus as keyof typeof purchaseStatusMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'purchasePaymentStatus'">
            <div gap-2>
              {{ purchasePaymentStatusMap[scope?.record?.purchasePaymentStatus as keyof typeof purchasePaymentStatusMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'remainSettlementAmount'">
            <div gap-2>
              <span :style="{ color: scope?.record?.remainSettlementAmount > 0 ? 'red' : '' }">
                {{ scope?.record?.remainSettlementAmount }}
              </span>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'purchaseActualAmount'">
            <div gap-2>
              <span :style="{ color: scope?.record?.purchaseActualAmount > 0 ? 'rgb(0, 128, 0)' : 'red' }">
                {{ scope?.record?.purchaseActualAmount }}
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <PurchaseAdd ref="purchaseAdd" />
    <PurchaseDetail ref="purchaseDetail" />
  </page-container>
</template>
